//
//  RecommendViewController.m
//  Happy Kitchen
//
//  Created by mac_chen on 15/3/7.
//  Copyright (c) 2015年 mac_chen. All rights reserved.
//

#import "RecommendViewController.h"

@interface RecommendViewController ()

@end

@implementation RecommendViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"热门推荐";
    
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:scrollView];
    
    
    //创建tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height - 64 - 49) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    
    
    [self.view addSubview:self.tableView];
    
    //指定代理人
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    

    //初始化属性字典和数组
    self.myRecommendDic = [NSMutableDictionary dictionary];
    self.myRecommendArray = [NSMutableArray array];
    
    
    //刷新
    //集成刷新控件
    [self addHeader];
    [self addFooter];
    
    
    //    ======================================================
    //    ======================================================
    
    //菊花
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    
    [self.view addSubview:self.HUD];
    self.HUD.labelText = @"加载中";
    [self.HUD showAnimated:YES whileExecutingBlock:^{
      
        NSLog(@"%@", @"加载中...");
        [self maxTime];
        
    } completionBlock:^{
        

        
    }];
    
    
    

    
    
//    ======================================================
//    ======================================================
    
    //滚动栏
    //取出数据
    NSMutableArray *mutableArray = [ImageTools getImagesArray];
    
    
    //布局大scrollView
    self.recommendContainerV = [[RecommendContainerView alloc] initWithFrame:CGRectMake(13, 8, self.tableView.frame.size.width - 26, 190) images:mutableArray];
    

    
    self.recommendContainerV.containDelegate = self;

    self.recommendContainerV.pushDelegate = self;
    
    
    //布局pageControl
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(300, self.recommendContainerV.frame.size.height - 30, self.recommendContainerV.frame.size.width - 300, 30)];
    self.pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    self.pageControl.currentPageIndicatorTintColor = [UIColor redColor];
//    self.pageControl.backgroundColor = [UIColor redColor];
    self.pageControl.numberOfPages = 4;
  

    

    //定时器
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(changeImageView) userInfo:nil repeats:YES];
    
    
}

//刷新时间上限
- (void)maxTime
{
    sleep(10);
}




- (void)changeImageView
{
    int page = (int)self.pageControl.currentPage;
    page++;
    page = page > 6 ? 0 : page;
    self.pageControl.currentPage = page;
    CGPoint offset = CGPointMake(self.recommendContainerV.frame.size.width * (page + 1), 0);
    [self.recommendContainerV setContentOffset:offset animated:YES];
}


#pragma mark -- containNerDelegate
- (void)changePageIndex:(NSInteger)index
{
    //接收代理传过来的下标
    self.pageControl.currentPage = index - 1;
}


- (void)pushAction:(NSInteger)index
{
    
    
    ScrollViewDetailViewController *scrollViewDVC = [[ScrollViewDetailViewController alloc] init];
    
    scrollViewDVC.index = index;
//    [self.svPushIndexDelegate pushIndexAction:scrollViewDVC.index];
    NSLog(@"%ld", scrollViewDVC.index);
    [self.navigationController pushViewController:scrollViewDVC animated:YES];
 
    
}


// 使用AFN进行数据请求
- (void) getClassifyListDetail: (NSInteger)nextPage
{
    
    

    NSString *url_Str = [NSString stringWithFormat:@"http://42.121.13.106:8080/HandheldKitchen/api/vegetable/tblvegetable!getNewTblVegetable.do?page=%ld&pageRecord=10&phonetype=0&is_traditional=0&user_id=", nextPage];
    
    [GetAFN downLoadBlock:url_Str block:^(id result) {
        
        if (self.isUpLoading == NO) {
            // 说明是下拉刷新，就要清空数组中的数据，保持数组中存放的是最新的数据
            [self.myRecommendArray removeAllObjects];
        }
        
        NSMutableDictionary *allClassifyDic = result;
        
        //记录下一页
        self.nextCursor = [[[allClassifyDic objectForKey:@"bean"] objectForKey:@"nextPageNumber"] integerValue];
        
        NSMutableArray *classifyArr = [allClassifyDic objectForKey:@"data"];
        
        for (NSMutableDictionary *dic in classifyArr) {
            Recommend *recommend = [[Recommend alloc] init];
            [recommend setValuesForKeysWithDictionary:dic];
            [self.myRecommendArray addObject:recommend];
        }
        
        NSLog(@"%@", self.myRecommendArray);
        
        //结束底部刷新效果
        [self.tableView footerEndRefreshing];
        //结束头部刷新效果
        [self.tableView headerEndRefreshing];
        // 刷新CollectionView
        [self.tableView reloadData];
        //加载完成,取消菊花
        [self.HUD removeFromSuperview];
        
        [self.tableView addSubview:self.recommendContainerV];
        [self.tableView addSubview:self.pageControl];
        

        
        
        
    }];
    
    
}


- (void)endFreshing
{
    [self.tableView headerEndRefreshing];
}

// 下拉刷新
- (void)addHeader
{
    __block RecommendViewController *recommendVC = self;
    // 添加下拉刷新头部控件
    [self.tableView addHeaderWithCallback:^{
        
        // 标记为下拉操作
        recommendVC.isUpLoading = NO;
        // 重新请求数据
        [recommendVC getClassifyListDetail:1];
        
    }];
    
    
    // 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    
}
// 上拉加载更多
- (void)addFooter
{
    __block RecommendViewController *recommendVC = self;
    // 添加上拉刷新尾部控件
    [self.tableView addFooterWithCallback:^{
        
        // 标记为上拉操作
        recommendVC.isUpLoading = YES;
        // 请求更多数据
        [recommendVC getClassifyListDetail:recommendVC.nextCursor];
    }];
    
    
}


//点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecommendDetailViewController *recommendDVC = [[RecommendDetailViewController alloc] init];
    //初始化model
    Recommend *recommend = [self.myRecommendArray objectAtIndex:indexPath.row];
    
//    NSLog(@"%@",recommendDVC.recommendDetailScorll.nameLabel );
    //传值
    recommendDVC.name = recommend.name;
    recommendDVC.vegetable_id = recommend.vegetable_id;
    
    
    [self.navigationController pushViewController:recommendDVC animated:YES];

}




//cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.myRecommendArray.count;
}





//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 210;
    }
    return 100;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    //自定义cell
    static NSString *cellIdentifier = @"reuse";
    RecommendTableViewCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[RecommendTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    cell.backgroundColor = [UIColor whiteColor];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    

    if (indexPath.row >= 1) {
        
        //获取model对象
        Recommend *recommend = [self.myRecommendArray objectAtIndex:indexPath.row];
        
        //请求图片
        NSString *urlStr = recommend.imagePathThumbnails;
        NSString *urlStrEncod = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:urlStrEncod];
        
        [cell.FoodImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"loading.jpg"]];
        
        //赋值
        cell.nameLabel.text = recommend.name;
        cell.clickLabel.text = recommend.clickCount;
        cell.effectLabel.text = recommend.effect;
//        NSLog(@"%@", cell);
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
    }
    
    
    
    return cell;

}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
